package com.gm;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

/**
 * Created by Administrator on 13-12-21.
 */
public class MouseComponent extends JComponent {
    public MouseComponent() {
        squares=new ArrayList<Rectangle2D>();
        current=null;

        addMouseListener(new MouseHandler());
        addMouseMotionListener(new MouseMotionHandler());

    }

    private ArrayList<Rectangle2D> squares;
    private Rectangle2D current;
    private static final int SLIDEWIDTH=10;

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D graph= (Graphics2D) g;

        for(Rectangle2D r:squares)
        {
            graph.draw(r);
        }
    }



    public Rectangle2D findRect(Point2D p)
    {
        for(Rectangle2D r:squares){
            if(r.contains(p))
                return r;
        }

        return null;
    }

    public void addRect(Point2D p)
    {
        double x=p.getX();
        double y=p.getY();

        Rectangle2D r=new Rectangle2D.Double(x-SLIDEWIDTH/2,y-SLIDEWIDTH/2,SLIDEWIDTH,SLIDEWIDTH);
        squares.add(r);
        repaint();

    }

    public void removeRect(Rectangle2D r)
    {
        if(r==null) return;
        if(r==current) current=null;

        squares.remove(r);
        repaint();
    }

    private class MouseHandler extends MouseAdapter
    {
        @Override
        public void mousePressed(MouseEvent e) {
            //super.mousePressed(e);

            Point2D p=e.getPoint();
            current=findRect(p);
            if(current==null) {
                addRect(p);
            }
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            //super.mouseClicked(e);

            current=findRect(e.getPoint());

            if(current!=null && e.getClickCount()>=2) {
                removeRect(current);
            }
        }
    }

    private class MouseMotionHandler implements MouseMotionListener{
        @Override
        public void mouseDragged(MouseEvent e) {

            if(current!=null)
            {
                int x=e.getX();
                int y=e.getY();

                current.setFrame(x-SLIDEWIDTH/2,y-SLIDEWIDTH/2,SLIDEWIDTH,SLIDEWIDTH);
                repaint();
            }
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            if(findRect(e.getPoint())==null)
            {
                setCursor(Cursor.getDefaultCursor());
            }
            else
                setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
        }
    }
}
